package com.mr.orderclient.service;

import com.mr.orderclient.api.ProductForOrderApi;
import com.mr.orderclient.dao.OrderDetailDAO;
import com.mr.orderclient.dao.OrderMasterDAO;
import com.mr.orderclient.entity.OrderDetail;
import com.mr.orderclient.entity.OrderMaster;
import com.mr.orderclient.entity.ProductInfo;
import com.mr.orderclient.exception.CustomException;
import com.mr.orderclient.utils.ConstantEnum;
import com.mr.orderclient.utils.UUIDUtil;
import com.mr.orderclient.utils.WebSocket;
import com.mr.orderclient.vo.CartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  OrderService
 *  MRui
 *  TODO 描述：订单service
 *  2018.09.20 22:00
 */
@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderMasterDAO orderMasterDAO;
    @Autowired
    private OrderDetailDAO orderDetailDAO;
    @Autowired
    private ProductForOrderApi productClient;
    /*@Autowired
    private ProductService productService;
    @Autowired
    private PayService payService;
    @Autowired
    private PushMessageService messageService;*/
    @Autowired
    private WebSocket webSocket;
    /**
    * User (作者)MRui
    * TODO (描述):创建订单
    * Date 2018.09.20 22:43
    */
    @Transactional
    public OrderMaster create(OrderMaster orderMaster){
        String orderId = UUIDUtil.getUUID();
        //定义总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        //1.查询商品(调用商品服务)
        List<String> productIds = orderMaster.getOrderDetailList().stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());
        List<ProductInfo> list = productClient.findList(productIds);
        //2.计算总价
        for (OrderDetail orderDetail : orderMaster.getOrderDetailList()) {
            for (ProductInfo productInfo : list){
                if (productInfo.getProductId().equals(orderDetail.getProductId())){
                    //计算订单总价（multiply:乘 BigDecimal的算法add:加）
                    orderAmount = productInfo.getProductPrice()
                            .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                            //累计
                            .add(orderAmount);
                    //订单详情入库
                    orderDetail.setDetailId(UUIDUtil.getUUID());
                    orderDetail.setOrderId(orderId);
                    BeanUtils.copyProperties(productInfo,orderDetail);
                    orderDetailDAO.save(orderDetail);
                }
            }
        }
        //3.写入订单数据库（orderMaster和orderDetail）
        /*OrderMaster orderM = new OrderMaster();
        BeanUtils.copyProperties(orderMaster,orderM);
        orderM.setOrderId(orderId);
        orderM.setOrderAmount(orderAmount);
        orderM.setOrderStatus(ConstantEnum.ORDER_NEW.getCode());
        orderM.setPay_status(ConstantEnum.PAY_WAIT.getCode());
        orderMasterDAO.save(orderM);*/
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(ConstantEnum.ORDER_NEW.getCode());
        orderMaster.setPayStatus(ConstantEnum.PAY_WAIT.getCode());
        orderMasterDAO.save(orderMaster);
        //4.扣库存
        List<CartVO> cartVOList = orderMaster.getOrderDetailList()
                .stream()
                .map(e -> new CartVO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.decreaseStock(cartVOList);
        //发送websocket消息
        webSocket.sendMessage("有新的订单:"+orderMaster.getOrderId());
        return  orderMaster;
    }
    /**
    * User (作者):MRui
    * TODO (描述):查询订单列表
    * Date 2018.09.20 22:45
    */
    public Page<OrderMaster> getOrderList(String buyerOpenid, Pageable pageable){
        Page<OrderMaster> orderMasterPage = orderMasterDAO.findByBuyerOpenid(buyerOpenid, pageable);
        orderMasterPage = new PageImpl<OrderMaster>(orderMasterPage.getContent(),pageable,orderMasterPage.getTotalElements());
        return orderMasterPage;
    }
    /**
    * User (作者): MRui
    * TODO (描述)：查询全部
    * Data：2018.09.27 22:22
    */
    public Page<OrderMaster> getOrderList(Pageable pageable){
        Page<OrderMaster> orderMasterPage = orderMasterDAO.findAll(pageable);
        orderMasterPage = new PageImpl<OrderMaster>(orderMasterPage.getContent(),pageable,orderMasterPage.getTotalElements());
        return orderMasterPage;
    }

    /**
    * User (作者):MRui
    * TODO (描述):查询单个订单（根据openId和orderId）
    * Date 2018.09.20 22:46
    */
    public OrderMaster getOrder(String openid, String orderId){
        OrderMaster orderMaster = orderMasterDAO.findByBuyerOpenidAndOrderId(openid,orderId);
        if (orderMaster == null){
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_NOT_EXIST);
        }
        List<OrderDetail> orderDetailList = orderDetailDAO.findByOrderId(orderId);
        if(orderDetailList.isEmpty()){
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_DETAIL_NOT_EXIST);
        }
        //订单详情列表
        orderMaster.setOrderDetailList(orderDetailList);
        return orderMaster;
    }
    /**
    * User (作者): MRui
    * TODO (描述)：查询单个订单（根据openId和orderId）
    * Data：2018.09.26 23:17
    */
    public OrderMaster getOrder(String orderId){
        OrderMaster orderMaster = orderMasterDAO.findByOrderId(orderId);
        if (orderMaster == null){
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_NOT_EXIST);
        }
        List<OrderDetail> orderDetailList = orderDetailDAO.findByOrderId(orderId);
        if(orderDetailList.isEmpty()){
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_DETAIL_NOT_EXIST);
        }
        //订单详情列表
        orderMaster.setOrderDetailList(orderDetailList);
        return orderMaster;
    }

    /**
    * User (作者):MRui
    * TODO (描述):取消订单
    * Date 2018.09.20 22:47
    */
    /*@Transactional
    public OrderMaster cancelOrder(OrderMaster orderMaster){
        //判断订单状态
        if (orderMaster.getOrderStatus()!=ConstantEnum.ORDER_NEW.getCode()){
            log.error("[取消订单]订单状态不正确，orderId={},orderStatus={}",orderMaster.getOrderId(),orderMaster.getOrderStatus());
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderMaster.setOrderStatus(ConstantEnum.ORDER_CANCEL.getCode());
        OrderMaster updateResult = orderMasterDAO.save(orderMaster);
        if (updateResult == null){
            log.error("[取消订单]更新失败，orderMaster={}",orderMaster);
            throw new CustomException(ConstantEnum.EXCEPTION_UPDATE_FAIL);
        }
        //返还库存
        if (CollectionUtils.isEmpty(orderMaster.getOrderDetailList())){
            log.error("[取消订单]更新失败，orderMaster={}",orderMaster);
            throw new CustomException(ConstantEnum.EXCEPTION_DETAIL_EMPTY);
        }
        List<CartVO> cartVOList = orderMaster.getOrderDetailList().stream()
                .map(e -> new CartVO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.increaseStock(cartVOList);
        //如果已支付 需要退款
        if (orderMaster.getPayStatus()==ConstantEnum.PAY_SUCCESS.getCode()){
            //payService.refund(orderMaster);
        }
        return orderMaster;
    }
    */
    /**
     * User (作者):MRui
     * TODO (描述):完结订单(微服务)
     * Date 2018.09.20 22:47
     */
    @Transactional
    public OrderMaster finishOrder(String orderId){
        //查询订单
        OrderMaster orderMaster = orderMasterDAO.findByOrderId(orderId);
        //判断订单状态
        if(orderMaster.getOrderStatus()!=ConstantEnum.ORDER_NEW.getCode()){
            log.error("[完结订单]订单状态不正确，orderId={},orderStatus={}",orderMaster.getOrderId(),orderMaster.getOrderStatus());
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderMaster.setOrderStatus(ConstantEnum.ORDER_FINISHED.getCode());
        OrderMaster updateState = orderMasterDAO.save(orderMaster);
        if (updateState == null){
            log.error("[取消订单]更新失败，orderMaster={}",orderMaster);
            throw new CustomException(ConstantEnum.EXCEPTION_UPDATE_FAIL);
        }
        //微信推送模板消息
        //messageService.pushOrderStatus(orderMaster);
        return orderMaster;
    }
    /**
    * User (作者):MRui
    * TODO (描述):完结订单(sell)
    * Date 2018.09.20 22:47
    */
    @Transactional
    public OrderMaster finishOrder(OrderMaster orderMaster){
        //判断订单状态
        if(orderMaster.getOrderStatus()!=ConstantEnum.ORDER_NEW.getCode()){
            log.error("[完结订单]订单状态不正确，orderId={},orderStatus={}",orderMaster.getOrderId(),orderMaster.getOrderStatus());
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderMaster.setOrderStatus(ConstantEnum.ORDER_FINISHED.getCode());
        OrderMaster updateState = orderMasterDAO.save(orderMaster);
        if (updateState == null){
            log.error("[取消订单]更新失败，orderMaster={}",orderMaster);
            throw new CustomException(ConstantEnum.EXCEPTION_UPDATE_FAIL);
        }
        //微信推送模板消息
        //messageService.pushOrderStatus(orderMaster);
        return orderMaster;
    }
    /**
    * User (作者):MRui
    * TODO (描述):支付订单
    * Date 2018.09.20 22:48
    *//*
    @Transactional
    public OrderMaster paidOrder(OrderMaster orderMaster){
        //判断订单状态
        if(orderMaster.getOrderStatus()!=ConstantEnum.ORDER_NEW.getCode()){
            log.error("[订单支付完成]订单状态不正确，orderId={},orderStatus={}",orderMaster.getOrderId(),orderMaster.getOrderStatus());
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_STATUS_ERROR);
        }
        //判断支付状态
        if (orderMaster.getPayStatus()!=ConstantEnum.PAY_WAIT.getCode()){
            log.error("[订单支付完成]订单支付状态不正确，orderId={}",orderMaster.getOrderId());
            throw new CustomException(ConstantEnum.EXCEPTION_PAY_STATUS_ERROR);
        }
        //修改支付状态
        orderMaster.setPayStatus(ConstantEnum.PAY_SUCCESS.getCode());
        OrderMaster updateState = orderMasterDAO.save(orderMaster);
        if (updateState == null){
            log.error("[订单支付完成]更新失败，orderMaster={}",orderMaster);
            throw new CustomException(ConstantEnum.EXCEPTION_UPDATE_FAIL);
        }
        return orderMaster;
    }*/
}
